const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const TerserPlugin = require('terser-webpack-plugin');
const PurifyCSS = require('purifycss-webpack');
const glob = require('glob-all');
const merge = require('webpack-merge');
const base = require('./webpack.base.config');

const resolve = dir => path.join(__dirname, dir);

const config = merge(base, {
	mode : 'production',
	entry : {
		main : resolve('src/main.js')
	},
	output : {
		path : resolve('dist'),
		filename : 'js/[name].[chunkhash:8].js'
	},
	optimization : {
		runtimeChunk : true,
		splitChunks : {
			chunks : 'all',
			minSize : 30000,
			minChunks : 1,
			maxAsyncRequests : 5,
			maxInitialRequests : 3,
			automaticNameDelimiter : '~',
			name : true,
			cacheGroups : {
				vendors : {
					test : /[\\/]node_modules[\\/]/,
					priority : -10,
					name : 'vendors'
				},
				default : {
					minChunks : 2,
					priority : -20,
					reuseExistingChunk : true,
					name : 'commons'
				}
			}
		},
		minimizer : [
			new TerserPlugin({
				terserOptions : {
					ecma : undefined,
					warnings : false,
					parse : {},
					compress : {
						drop_console : true,
						drop_debugger : true,
						pure_funcs : ['console.log'] // 移除console
					}
				}
			}),
			new OptimizeCssAssetsPlugin({
				cssProcessor : require('cssnano'),
				cssProcessorOptions : {
					discardComments : {
						removeAll : true
					}
				},
				canPrint : true
			})
		]
	},
	plugins : [
		new CleanWebpackPlugin(),
		// 清除⽆无⽤用 cssc
		new PurifyCSS({
			paths : glob.sync([
				path.resolve(__dirname, './src/*.html'),
				path.resolve(__dirname, './src/*.js'),
				path.resolve(__dirname, './src/*.jsx')
			])
		}),
		new HtmlWebpackPlugin({
			template : resolve('index.html'),
			favicon : resolve('favicon.ico'),
			hash : false,
			minify : {
				caseSensitive : false,
				removeEmptyAttributes : true,
				removeComments : true, // 移除HTML中的注释
				collapseWhitespace : true, // 删除空⽩白符与换⾏行行符
				minifyCSS : true // 压缩内联css
			}
		})
	]
});
if (process.env.ANALY) {
	config.plugins.push(new BundleAnalyzerPlugin());
}
module.exports = config;
